<?php
// $Id$

/**
 * @file
 */

/**
 * Form builder;
 *
 * @see theme_guild_admin_ranks_form()
 */
function guild_admin_ranks_form() {
  $form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => '',
    '#size' => 40,
    '#maxlength' => 32
  );
  
  $form['tier'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(range(0, 10)),
    '#default_value' => 0
  );
  
  // Manually entered ranks belong to this module.
  $form['module'] = array('#type' => 'value', '#value' => 'guild');
  
  $form['add_rank'] = array(
    '#type' => 'submit',
    '#value' => t('Add rank'),
    '#validate' => array('guild_admin_add_rank_validate'),
    '#submit' => array('guild_admin_add_rank_submit')
  );
  
  $ranks = guild_get_ranks(TRUE);
  
  //$form['weights'] = array('#tree' => TRUE);
  foreach ($ranks as $id => $rank) {
    $form['names'][$id] = array('#value' => check_plain($rank->name));
    $form['tiers'][$id] = array(
      '#type' => 'select',
      '#options' => drupal_map_assoc(range(0, 10)),
      '#default_value' => $rank->tier,
      '#disabled' => ($rank->locked != GUILD_RANK_NORMAL) ? TRUE : FALSE
    );
    
    $form['edit'][$id] = array('#value' => ($rank->locked == GUILD_RANK_READ_ONLY) ? t('locked') : l(t('edit'), 'admin/guild/ranks/' . $rank->rank_id . '/edit'));
    $form['delete'][$id] = array('#value' => $rank->module != 'guild' ? '' : l(t('delete'), 'admin/guild/ranks/' . $rank->rank_id . '/delete'));
  }
  
  //$form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
  
  return $form;
}

/**
 * @ingroup themeable
 */
function theme_guild_admin_ranks_form($form) {
  $header = array(t('Name'), t('Tier'), array('data' => t('Operations'), 'colspan' => 2));
  $rows = array();
  
  foreach (element_children($form['names']) as $id) {
    if (is_array($form['names'][$id])) {
      $form['tiers'][$id]['#attributes']['class'] = 'rank-order-tier';
      $rows[] = array(
        'data' => array(
          drupal_render($form['names'][$id]),
          drupal_render($form['tiers'][$id]),
          drupal_render($form['edit'][$id]),
          drupal_render($form['delete'][$id])
        ),
        //'class' => 'draggable'
      );
    }
  }
  
  //if (empty($rows)) {
  //  $rows[] = array(array('data' => t('No ranks defined.'), 'colspan' => '4'));
  //}
  
  $rows[] = array(
    drupal_render($form['name']),
    drupal_render($form['tier']),
    array('data' => drupal_render($form['add_rank']), 'colspan' => 2)
  );
  
  //$output = drupal_render($form['create']);
  
  $output = theme('table', $header, $rows, array('id' => 'rank-order'));
  $output .= drupal_render($form);
  
  //drupal_add_tabledrag('rank-order', 'order', 'sibling', 'rank-order-tier', NULL, NULL, FALSE);
  
  return $output;
}

/**
 * Validate admin_create_rank form values.
 */
function guild_admin_add_rank_validate($form, &$form_state) {
  if (empty($form_state['values']['name'])) {
    form_set_error('name', t('You must specify a valid rank name.'));
  }
}

/**
 * Save a new rank into the database and log the event.
 */
function guild_admin_add_rank_submit($form, &$form_state) {
  $values = $form_state['values'];
  $t_args = array('%name' => $values['name']);
  
  drupal_write_record('guild_rank', $values);
  watchdog('guild', 'rank: added %name.', $t_args);
  
  drupal_set_message(t('Added rank %name.', $t_args));
}

function guild_ranks_edit($form_state, $op, $rank = NULL) {
  if (empty($rank) || $op == 'add') {
    // This should be unreachable, but whatever...
    $rank = array(
      'rank_id' => NULL,
      'name' => '',
      'tier' => 0,
      'locked' => GUILD_RANK_NORMAL,
      'module' => 'guild'
    );
  }
  else {
    drupal_set_title(t('Editing rank: @name', array('@name' => $rank['name'])));
  }
  
  $form['rank_op'] = array('#type' => 'value', '#value' => $op);
  $form['rank_id'] = array('#type' => 'value', '#value' => $rank['rank_id']);
  $form['module'] = array('#type' => 'value', '#value' => $rank['module']);
  
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Rank name'),
    '#default_value' => $rank['name'],
    '#required' => TRUE,
    '#disabled' => $rank['locked'] == GUILD_RANK_READ_ONLY ? TRUE : FALSE
  );
  
  $form['tier'] = array(
    '#type' => 'select',
    '#title' => t('Rank tier'),
    '#options' => drupal_map_assoc(range(0, 10)),
    '#default_value' => $rank['tier'],
    '#disabled' => $rank['locked'] != GUILD_RANK_NORMAL ? TRUE : FALSE
  );
  
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $op == 'add' ? t('Add rank') : t('Update'),
    '#disabled' => $rank['locked'] == GUILD_RANK_READ_ONLY ? TRUE : FALSE
  );
  
  return $form;
}

function guild_ranks_edit_validate($form, &$form_state) {
  // @todo Enforce unique rank names?
}

/**
 *
 */
function guild_ranks_edit_submit($form, &$form_state) {
  $values = $form_state['values'];
  $t_args = array('%name' => $values['name']);
  
  if ($values['rank_op'] == 'edit') {
    drupal_write_record('guild_rank', $values, 'rank_id');
    watchdog('guild', 'rank: updated %name', $t_args);
    
    drupal_set_message(t('The rank %name has been updated.', $t_args));
  }
  
  $form_state['redirect'] = 'admin/guild/ranks';
}

/**
 *
 */
function guild_ranks_delete_confirm(&$form_state, $op, $rank) {
  $form['rank_id'] = array('#type' => 'value', '#value' => $rank['rank_id']);
  $form['name'] = array('#type' => 'value', '#value' => $rank['name']);
  
  // @todo Should we only delete ranks belonging to this module?
  //if ($rank['module'] != 'guild') {
  //  drupal_set_message(t(''), 'error');
  //}
  
  $message = t('Are you sure you want to delete the %rank rank?', array('%rank' => $rank['name']));
  $caption = '';
  
  $in_use = db_result(db_query(
    "SELECT COUNT(*) FROM {node} n " .
    "INNER JOIN {guild_member} m USING(nid) " .
    "WHERE m.rank_id = %d", $rank['rank_id']
  ));
  
  if ($in_use) {
    $caption .= '<p>' . format_plural($in_use,
      '<strong>Warning:</strong> This rank is in use by 1 member.',
      '<strong>Warning:</strong> This rank is in use by @count members.'
    ) . '</p>';
  }
  
  $caption .= '<p>' . t('This action cannot be undone.') . '</p>';
  
  return confirm_form($form, $message, 'admin/guild/ranks', $caption, t('Delete'));
}

/**
 *
 */
function guild_ranks_delete_confirm_submit($form, &$form_state) {
  $rank = $form_state['values'];
  $t_args = array('%name' => $rank['name']);
  
  db_query("DELETE FROM {guild_rank} WHERE rank_id = %d", $rank['rank_id']);
  watchdog('guild', 'rank: deleted rank %name', $t_args);
  
  drupal_set_message(t('The rank %name has been deleted.', $t_args));
  
  $form_state['redirect'] = 'admin/guild/ranks';
  return;
}
